from parsermk.cmdparser import DataCmdParser

NotFoundStrategy = {
    "ignore" : 0,
    "except" : 1,
}

class DataBtnParser:
    """ Page中的一组Buttons的集合对象 """
    def __init__(self, dict_btnlist):
        self.dict_btns_data = dict_btnlist

    def data_items(self):
        """ return an iterator of buttons' id """
        return self.dict_btns_data.items()

    def check_attribute(self, id, key, not_found_strategy):
        """ return a string of attribute value """
        if key not in self.dict_btns_data[id][1]:
            if not_found_strategy == NotFoundStrategy["ignore"]:
                return ""
            elif not_found_strategy == NotFoundStrategy["except"]:
                raise Exception("No such attribute [%s] in button[%s]" % (key, id))
        else:
            return self.dict_btns_data[id][1][key]

    def geometry(self, id):
        """ return [x, y, w, h] """
        return [int(self.check_attribute(id, str_key, NotFoundStrategy["except"])) 
                for str_key in ["x", "y", "w", "h"] ]

    def text(self, id):
        """ return string of button attribute["text"] """
        return self.check_attribute(id, "text", NotFoundStrategy["ignore"])

    def sticky(self, id):
        """ return bool of the sticky status,
            if not found [sticky] attribute, return False.
        """
        return self.check_attribute(id, "sticky", NotFoundStrategy["ignore"]) == "true"

    def image(self, id):
        """ return the str_path of image,
            if not found attrib, return NULL string;
        """
        return self.check_attribute(id, "image", NotFoundStrategy["ignore"])

    def get_cmd_parser(self, id):
        """ return an object of cmd parser """
        return DataCmdParser(id, self.dict_btns_data[id][2])
